package com.cloudcentral.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudcentral.entity.Menu;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.feign.ToolkitFeign;
import com.cloudcentral.mapper.MenuMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 系统菜单表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2023-10-27
 */
@Slf4j
@Service
public class MenuService extends ServiceImpl<MenuMapper, Menu> {
  private final ToolkitFeign toolkitFeign;

  @Autowired
  public MenuService(ToolkitFeign toolkitFeign) {
    this.toolkitFeign = toolkitFeign;
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Menu submit(Menu menu) throws Exception {
    if (menu.getPlatformId() == null) throw new FailureException("缺少平台ID");
    else if (StringUtils.isBlank(menu.getLabel())) throw new FailureException("缺少名称");
    else if (StringUtils.isBlank(menu.getPath())) throw new FailureException("缺少路径");
    else {
      saveOrUpdate(menu);
      return getById(menu.getId());
    }
  }

  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public Boolean delete(Long id) throws Exception {
    Menu menu = getById(id);
    removeById(id);
    toolkitFeign.delete(menu.getIcon());
    return true;
  }

  public List<Menu> listByUser(Long platformId, Long userId) {
    return baseMapper.listByUser(platformId, userId);
  }
}
